package com.prs.crm.action.cqunicom;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.action.ReportAction;
import com.prs.crm.annotation.Clew;
import com.prs.crm.context.AppContext;
import com.prs.crm.domain.cqunicom.BusinessOrder;
import com.prs.crm.domain.cqunicom.Company;
import com.prs.crm.domain.cqunicom.LogSerch;
import com.prs.crm.domain.cqunicom.MonitorOrder;
import com.prs.crm.domain.cqunicom.OrderReconciliation;
import com.prs.crm.domain.cqunicom.PoplarOrder;
import com.prs.crm.domain.cqunicom.Services;
import com.prs.crm.domain.cqunicom.ServicesType;
import com.prs.crm.report.ExportConfig;
import com.prs.crm.report.ReportCell;
import com.prs.crm.report.ReportTable;
import com.prs.crm.service.cqunicom.BusinessOrderService;
import com.prs.crm.service.cqunicom.CompanyService;
import com.prs.crm.service.cqunicom.LogSerchService;
import com.prs.crm.service.cqunicom.MonitorOrderService;
import com.prs.crm.service.cqunicom.OrderReconciliationService;
import com.prs.crm.service.cqunicom.OrderService;
import com.prs.crm.service.cqunicom.ServicesService;
import com.prs.crm.service.cqunicom.ServicesTypeService;

/**
 * @author LanXiaoGang
 * @E-mail:lan9liang@163.com
 * @qq:7857553326
 * @version 创建时间：2011-3-14 下午04:15:26 简单说明
 */

public class OrderReconciliationAction extends ReportAction {

	private static final long serialVersionUID = 1L;

	private PaginationSupport pagination;

	private Company company;

	private String rowdata;

	private Integer sid;
	
	private LogSerchService logSerchService;
	private BusinessOrder businessOrder;

	private List<ServicesType> serverList;

	private List<Services> serverssList;

	private OrderReconciliation orderReconciliation;
	
	private OrderReconciliationService orderReconciliationService;
	
	private BusinessOrderService businessOrderService;

	private MonitorOrder monitorOrder;

	private MonitorOrderService monitorOrderService;

	private CompanyService companyService;

	private PoplarOrder order;

	private OrderService orderService;

	private Services services;

	private ServicesService servicesService;

	private ServicesType servicesType;

	private ServicesTypeService servicesTypeService;

	private String conditionss="";
	
	private OrderCount orderCount=new OrderCount();

	private String dateSletct="";

	private Date startTimes=null;

	private Date endTimes=null;

	private String sortStyle="差异排序";
	
	private Integer derstys=0;

	private Integer serveess=0;

	private String companysNames="";
	
	private String cusName;

	private String dealStates="";
    //显示统计
	//时间
	private String starts="";
	private String ends="";
	

	@Action("serchCustomers")
	public String serchCustomers() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Company.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getCompanyService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}
	
	
	
	@Action("listOrderCountNext")
	public String listOrderCountNext() {
		 SimpleDateFormat ddf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		 
		  if(startTimes==null){
			  Calendar c = Calendar.getInstance();
			  c.add(Calendar.DAY_OF_MONTH, -7);
			  Date _currt=c.getTime();
			  starts=ddf.format(_currt);//开始时间  
		  }else{
			  starts=ddf.format(startTimes); 
		  }
		  if(endTimes==null){
			 ends=ddf.format(new Date());//结束时间 
		  }else{
			  ends=ddf.format(endTimes);
		  }
		
		// 服务类别集合
		serverList = this.getServicesTypeService().getAllServicesType();
		//System.out.println(serverList.size()+"serverList");
		
		List<PoplarOrder> s1=this.getOrderService().getAllBydealState("所有");
        List<PoplarOrder> s2=this.getOrderService().getAllBydealState("已成交");
        List<PoplarOrder> s3=this.getOrderService().getBydealState("已成交");
       
        orderCount.setAccptAmount(s1.size()+"");//总结单量
        orderCount.setTransactionAmount(s2.size()+"");//总成交量
        int s1Lengths=s1.size();
      // System.out.println("s1Lengths:"+s1Lengths);
        if(s1Lengths>0){
        	 orderCount.setTransactionRate((s2.size()/s1.size()*100)+"%");//成交率
        }else{
        	 orderCount.setTransactionRate("0%");//成交率
        }
        //System.out.println("成交率:"+orderCount.getTransactionRate());
       
        Double g=0.0;
        for(PoplarOrder LL:s2){
        	g=g+LL.getBusinessOrder().getDealPrice();
        }
        orderCount.setTransactionPrice(g+"");//总成交价
        int s2length=s2.size();
        String yycjlv="0";
        if(s2length>0){
        	  yycjlv=(s3.size()/s2.size()*100)+"%";
        }else{
        	yycjlv="0%";
        }
       
        orderCount.setYyTransactionRate(yycjlv);//yyTransactionRate
		//System.out.println("价格："+orderCount.getTransactionPrice());
		
		
		//System.out.println("conditionss:" + conditionss);
		if ("".equals(conditionss) || conditionss == null) {
		//条件为空时候	
			DetachedCriteria criteria = this.getPaginationHelper().createQuery(PoplarOrder.class);
			criteria.add(Restrictions.eq("modleName", "派单"));		
			pagination = this.getPaginationHelper().prepare(pagination);
			this.setPagination(this.getOrderService().listByPage(criteria,pagination));
		
		} else {
			//System.out.println("查询条件不为空的时候");
			DetachedCriteria criteria = this.getPaginationHelper().createQuery(PoplarOrder.class);
			criteria.add(Restrictions.eq("modleName", "派单"));
			//设置是否排序
			//System.out.println("设置是否排序:"+sortStyle);
			if (sortStyle.equals("时间")) {
				criteria.addOrder(Order.asc("recordTime"));
			}
			//System.out.println("处理状态dealStates:"+dealStates);
			
			
			if ("所有".equals(conditionss)) {
			} else if ("服务类别".equals(conditionss)) {		
				//System.out.println("服务名称:"+serveess);
				Services  hk=this.getServicesService().get(serveess);
				//System.out.println("服务ID："+hk.getId());
				criteria.add(Restrictions.eq("services", hk));
			} else if ("公司名称".equals(conditionss)) {
				if (!"".equals(companysNames)) {
					//System.out.println("公司名称:"+companysNames);
					Company com=this.getCompanyService().get(Integer.parseInt(companysNames));
					companysNames=com.getComName();
					criteria.add(Restrictions.eq("company", com));
				}

			}
			criteria.createAlias("businessOrder", "bu");
			if ("派单时间".equals(dateSletct)) {
				
				criteria.add(Restrictions.between("orderDate", startTimes,
						endTimes));
			} else if ("完成时间".equals(dateSletct)) {
				criteria.add(Restrictions.between("compleDate", startTimes,
						endTimes));
			} else if ("预约时间".equals(dateSletct)) {

				criteria.add(Restrictions.between("bu.rserveTime", startTimes,
						endTimes));
			}
			if ("所有".equals(dealStates)) {

			} else {
				
				criteria.add(Restrictions.eq("bu.transationSatet", dealStates));
			}
			pagination = this.getPaginationHelper().prepare(pagination);
			this.setPagination(this.getOrderService().listByPage(criteria,
					pagination));

		} 
		return SUCCESS;
	}
	
	@Action(value = "exportOrderCountReport", results = { @Result(name = "success", type = "stream", params = {
			"contentType", "${contentType}", "inputName", "inputStream",
			"bufferSize", "1024", "contentDisposition",
			"filename=${outfileName}" }) })
	public String reportOrderCount() {
		
		ReportTable table = new ReportTable("订单报表");
		table.addCell(new ReportCell("订单号", "orderCode"));
		table.addCell(new ReportCell("客户名称", "customerName"));
		table.addCell(new ReportCell("客户电话", "customerTel"));
		table.addCell(new ReportCell("交易状态", "businessOrder.transationSatet"));
		table.addCell(new ReportCell("成交价格", "businessOrder.dealPrice"));
		table.addCell(new ReportCell("下单时间","orderDate"));
		table.addCell(new ReportCell("公司名称", "comName"));
		table.addCell(new ReportCell("回访状态", "monitorOrder.visitState"));
		table.addCell(new ReportCell("满意度", "monitorOrder.enjoyDegree"));
		table.addCell(new ReportCell("派单人员", "businessOrder.outPerson"));
		 SimpleDateFormat ddf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		 
		  if(startTimes==null){
			  Calendar c = Calendar.getInstance();
			  c.add(Calendar.DAY_OF_MONTH, -7);
			  Date _currt=c.getTime();
			  starts=ddf.format(_currt);//开始时间  
		  }else{
			  starts=ddf.format(startTimes); 
		  }
		  if(endTimes==null){
			 ends=ddf.format(new Date());//结束时间 
		  }else{
			  ends=ddf.format(endTimes);
		  }
		
		// 服务类别集合
		serverList = this.getServicesTypeService().getAllServicesType();
		//System.out.println(serverList.size()+"serverList");
		
		List<PoplarOrder> s1=this.getOrderService().getAllBydealState("所有");
       List<PoplarOrder> s2=this.getOrderService().getAllBydealState("已成交");
       List<PoplarOrder> s3=this.getOrderService().getBydealState("已成交");
       orderCount.setAccptAmount(s1.size()+"");
       orderCount.setTransactionAmount(s2.size()+"");
       int s1Lengths=s1.size();
       String cjlv="0%";
       if(s1Lengths>0){
       	cjlv=(s2.size()/s1Lengths)*100+"%";
       }
       
       orderCount.setTransactionRate(cjlv);
       Double g=0.0;
       for(PoplarOrder LL:s2){
       	g=g+LL.getBusinessOrder().getDealPrice();
       }
       orderCount.setTransactionPrice(g+"");
       int s2length=s2.size();
       String yycjlv="0";
       if(s2length>0){
       	  yycjlv=(s3.size()/s2.size()*100)+"%";
       }
      
       orderCount.setYyTransactionRate(yycjlv);
		//System.out.println("价格："+orderCount.getTransactionPrice());
		
		
		//System.out.println("conditionss:" + conditionss);
		if ("".equals(conditionss) || conditionss == null) {
		//条件为空时候	
			DetachedCriteria criteria = this.getPaginationHelper().createQuery(PoplarOrder.class);
			criteria.add(Restrictions.eq("modleName", "派单"));		
			pagination = this.getPaginationHelper().prepare(pagination);
			this.setPagination(this.getOrderService().listByPage(criteria,pagination));
		
			this.setOutFilePath(this.getReportService().report(criteria, table,
					new ExportConfig(), this.getExportType()));
			return SUCCESS;

		} else {
			//System.out.println("查询条件不为空的时候");
			DetachedCriteria criteria = this.getPaginationHelper().createQuery(PoplarOrder.class);
			criteria.add(Restrictions.eq("modleName", "派单"));
			//设置是否排序
			//System.out.println("设置是否排序:"+sortStyle);
			if (sortStyle.equals("时间")) {
				criteria.addOrder(Order.asc("recordTime"));
			}
			//System.out.println("处理状态dealStates:"+dealStates);
			
			
			if ("所有".equals(conditionss)) {
			} else if ("服务类别".equals(conditionss)) {		
				//System.out.println("服务名称:"+serveess);
				Services  hk=this.getServicesService().get(serveess);
				//System.out.println("服务ID："+hk.getId());
				criteria.add(Restrictions.eq("services", hk));
			} else if ("公司名称".equals(conditionss)) {
				if (!"".equals(companysNames)) {
					//System.out.println("公司名称:"+companysNames);
					Company com=this.getCompanyService().get(Integer.parseInt(companysNames));
					companysNames=com.getComName();
					criteria.add(Restrictions.eq("company", com));
				}

			}
			criteria.createAlias("businessOrder", "bu");
			if ("派单时间".equals(dateSletct)) {
				
				criteria.add(Restrictions.between("bu.outDate", startTimes,
						endTimes));
			} else if ("完成时间".equals(dateSletct)) {
				criteria.add(Restrictions.between("compleDate", startTimes,
						endTimes));
			} else if ("预约时间".equals(dateSletct)) {

				criteria.add(Restrictions.between("bu.rserveTime", startTimes,
						endTimes));
			}
			if ("所有".equals(dealStates)) {

			} else {
				
				criteria.add(Restrictions.eq("bu.transationSatet", dealStates));
			}
			pagination = this.getPaginationHelper().prepare(pagination);
			this.setPagination(this.getOrderService().listByPage(criteria,
					pagination));

			this.setOutFilePath(this.getReportService().report(criteria, table,
					new ExportConfig(), this.getExportType()));
			return SUCCESS;
		} 
		
		
	}

	
	
	
	/**
	 * 创建对账信息
	 * @return
	 */
	@Clew(results = { "success", "none" })
	@Action(value = "newAddOrderRations", results = {
			@Result(name = "success", type = "redirect", location = "listOrderCountNext"),
			@Result(name = "none", type = "redirect", location = "listOrderCountNext"),
			@Result(name = "error", type = "chain", location = "listOrderCountNext") })
	public String newAddOrderRations() {
		Company com=this.getCompanyService().get(Integer.parseInt(companysNames));
		List<PoplarOrder>  skList=this.getOrderService().getBycompany(com);
		double totls=0.0;
		double cusTotl=0.0;
		for(PoplarOrder p:skList){
			if(p.getBusinessOrder()!=null){
				if(p.getBusinessOrder().getDealPrice()!=null){
				cusTotl=cusTotl+p.getBusinessOrder().getDealPrice();
				}
			}
			if(p.getMonitorOrder()!=null){
				if(p.getMonitorOrder().getTradeAmount()!=null){
					totls=totls+p.getMonitorOrder().getTradeAmount();
				}
			}
			
		}
		OrderReconciliation  or=new OrderReconciliation();
		or.setCompanyy(com);
		or.setDealPrice(cusTotl);
		or.setSendTime(new Date());
		or.setStartTime(startTimes);
		or.setEndTime(endTimes);
		or.setHavaProplem("否");
		or.setBackInf("是");
		or.setTotlePrice(totls);
		or.setRemarks(orderReconciliation.getRemarks());
		or.setBunisePrice(cusTotl);
		this.getOrderReconciliationService().save(or);

		LogSerch  log=new LogSerch();
		log.setCandlePeron(AppContext.getAccountContext().currentUser().getUserName());
		log.setCandleContents("进行了对账数据信息发送");
		this.getLogSerchService().save(log);
		
		this.setPrompt("对账数据信息发送中请稍等......");
		return SUCCESS;
	}
/**
 * 公司查询
 */
	@Action(value = "serchsCusTomer", results = { @Result(name = "success", type = "json", params = {
			"root", "rowdata" }) })
	public String serchsCusTomer() {
		//System.out.println("cusName："+cusName);
		Company cn=this.getCompanyService().get(Integer.parseInt(cusName));
		if(cn==null){
			this.rowdata = null;
		}else{
			this.rowdata = "gg";
		}
		
		return SUCCESS;
	}
/**
 * 对账信息查询	
 * @return
 */

	@Action("listOrderReconciliation")
	public String listOrderReconciliation() {	
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				OrderReconciliation.class);
		pagination = this.getPaginationHelper().prepare(pagination);	
		if(AppContext.getAccountContext().getUser().getRole().getId()==9){
			criteria.add(Restrictions.eq("companyy", AppContext.getAccountContext().getUser().getCompanys()));
		}
		this.setPagination(this.getOrderReconciliationService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	
	
	@Action("listOrderCount")
	public String listOrderCount() {
		return SUCCESS;
	}

	@Action("editOrderCountUp")
	public String editOrderCountUp() {

		return SUCCESS;
	}

	@Action(value = "serchServer", results = { @Result(name = "success", type = "json", params = {
			"root", "rowdata" }) })
	public String serchServer() {
		//System.out.println("sid:" + sid);
		ServicesType st = this.getServicesTypeService().get(sid);
		this.serverssList = this.getServicesService().getByStyle(st);
		String rows = "";
		for (Services s : serverssList) {
			String ok = s.getId() + "-" + s.getName();
			if ("".equals(rows)) {
				rows = ok;
			} else {
				rows = rows + "," + ok;
			}
		}
		this.rowdata = rows;
		return SUCCESS;
	}

	@Action("lookOrderReconciliation")
	public String lookOrderReconciliation() {

		return SUCCESS;
	}
	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public String getDateSletct() {
		return dateSletct;
	}

	public void setDateSletct(String dateSletct) {
		this.dateSletct = dateSletct;
	}

	public Date getStartTimes() {
		return startTimes;
	}

	public String getDealStates() {
		return dealStates;
	}

	public void setDealStates(String dealStates) {
		this.dealStates = dealStates;
	}

	public void setStartTimes(Date startTimes) {
		this.startTimes = startTimes;
	}

	public Date getEndTimes() {
		return endTimes;
	}

	public void setEndTimes(Date endTimes) {
		this.endTimes = endTimes;
	}

	public Company getCompany() {
		return company;
	}

	public void setCompany(Company company) {
		this.company = company;
	}

	public String getConditionss() {
		return conditionss;
	}

	public Integer getServeess() {
		return serveess;
	}

	public void setServeess(Integer serveess) {
		this.serveess = serveess;
	}

	public void setConditionss(String conditionss) {
		this.conditionss = conditionss;
	}

	public BusinessOrder getBusinessOrder() {
		return businessOrder;
	}

	public Integer getSid() {
		return sid;
	}

	public String getRowdata() {
		return rowdata;
	}

	public void setRowdata(String rowdata) {
		this.rowdata = rowdata;
	}

	public void setSid(Integer sid) {
		this.sid = sid;
	}

	public void setBusinessOrder(BusinessOrder businessOrder) {
		this.businessOrder = businessOrder;
	}

	public BusinessOrderService getBusinessOrderService() {
		return businessOrderService;
	}

	public List<Services> getServerssList() {
		return serverssList;
	}

	public void setServerssList(List<Services> serverssList) {
		this.serverssList = serverssList;
	}

	public void setBusinessOrderService(
			BusinessOrderService businessOrderService) {
		this.businessOrderService = businessOrderService;
	}

	public MonitorOrder getMonitorOrder() {
		return monitorOrder;
	}

	public void setMonitorOrder(MonitorOrder monitorOrder) {
		this.monitorOrder = monitorOrder;
	}

	public MonitorOrderService getMonitorOrderService() {
		return monitorOrderService;
	}

	public void setMonitorOrderService(MonitorOrderService monitorOrderService) {
		this.monitorOrderService = monitorOrderService;
	}

	public CompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	public PoplarOrder getOrder() {
		return order;
	}

	public void setOrder(PoplarOrder order) {
		this.order = order;
	}

	public OrderService getOrderService() {
		return orderService;
	}

	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	public Services getServices() {
		return services;
	}

	public void setServices(Services services) {
		this.services = services;
	}

	public ServicesService getServicesService() {
		return servicesService;
	}

	public void setServicesService(ServicesService servicesService) {
		this.servicesService = servicesService;
	}

	public ServicesType getServicesType() {
		return servicesType;
	}

	public void setServicesType(ServicesType servicesType) {
		this.servicesType = servicesType;
	}

	public ServicesTypeService getServicesTypeService() {
		return servicesTypeService;
	}

	public void setServicesTypeService(ServicesTypeService servicesTypeService) {
		this.servicesTypeService = servicesTypeService;
	}

	public List<ServicesType> getServerList() {
		return serverList;
	}

	public void setServerList(List<ServicesType> serverList) {
		this.serverList = serverList;
	}

	public String getSortStyle() {
		return sortStyle;
	}

	public void setSortStyle(String sortStyle) {
		this.sortStyle = sortStyle;
	}

	public String getCompanysNames() {
		return companysNames;
	}

	public void setCompanysNames(String companysNames) {
		this.companysNames = companysNames;
	}

	public OrderCount getOrderCount() {
		return orderCount;
	}

	public void setOrderCount(OrderCount orderCount) {
		this.orderCount = orderCount;
	}

	public OrderReconciliation getOrderReconciliation() {
		return orderReconciliation;
	}

	public void setOrderReconciliation(OrderReconciliation orderReconciliation) {
		this.orderReconciliation = orderReconciliation;
	}

	public OrderReconciliationService getOrderReconciliationService() {
		return orderReconciliationService;
	}

	public void setOrderReconciliationService(
			OrderReconciliationService orderReconciliationService) {
		this.orderReconciliationService = orderReconciliationService;
	}
	public String getStarts() {
		return starts;
	}
	public void setStarts(String starts) {
		this.starts = starts;
	}
	public String getEnds() {
		return ends;
	}
	public void setEnds(String ends) {
		this.ends = ends;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	public Integer getDerstys() {
		return derstys;
	}
	public void setDerstys(Integer derstys) {
		this.derstys = derstys;
	}
	public String getCusName() {
		return cusName;
	}
	public void setCusName(String cusName) {
		this.cusName = cusName;
	}
	public LogSerchService getLogSerchService() {
		return logSerchService;
	}
	public void setLogSerchService(LogSerchService logSerchService) {
		this.logSerchService = logSerchService;
	}

}
